﻿namespace Dcms.Common
{
    using Dcms.Config;
    using System;
    using System.Collections;
    using System.IO;
    using System.Runtime.CompilerServices;
    using System.Web;
    using System.Web.Caching;
    using System.Xml;
    using System.Configuration;

    public class SiteUrls
    {
        private ArrayList _Urls;
        private static volatile SiteUrls instance = null;
        private static object lockHelper = new object();
        private string SiteUrlsFile = HttpContext.Current.Server.MapPath("~/SystemConfig/url.config");
        private static readonly string WebSitePath = ConfigurationManager.AppSettings["WebSite"];

        private SiteUrls()
        {
            this.Urls = new ArrayList();
            XmlDocument xml = new XmlDocument();
            xml.Load(this.SiteUrlsFile);
            XmlNode root = xml.SelectSingleNode("urls");
            foreach (XmlNode n in root.ChildNodes)
            {
                if (n.NodeType != XmlNodeType.Comment && n.Name.ToLower() == "rewrite")
                {
                    XmlAttribute name = n.Attributes["name"];
                    XmlAttribute path = n.Attributes["path"];
                    XmlAttribute page = n.Attributes["page"];
                    XmlAttribute value = n.Attributes["value"];
                    URLRewrite URL = new URLRewrite(name.Value, path.Value, page.Value, Convert.ToInt32(value.Value));
                    this.Urls.Add(URL);
                }
            }
        }

        public static SiteUrls GetSiteUrls()
        {
            FileInfo webInfo = new FileInfo(HttpContext.Current.Server.MapPath("~/SystemConfig/WebSiteInfo.config"));
            if (Utils.GetDiffDate(webInfo.LastWriteTime, DateTime.Now, 3) < 4)
            {
                Cache Cache = HttpRuntime.Cache;
                string snCode = WebSiteConfigs.Deserialize("~/SystemConfig/WebSiteInfo.config").snCode;
                Cache.Insert("snCode", snCode);
            }
            FileInfo fi = new FileInfo(HttpContext.Current.Server.MapPath("~/SystemConfig/url.config"));
            if (Utils.GetDiffDate(fi.LastWriteTime, DateTime.Now, 3) < 4) instance = null;
            if (instance == null)
            {
                lock (lockHelper)
                {
                    if (instance == null) instance = new SiteUrls();
                }
            }
            return instance;
        }

        public ArrayList Urls
        {
            get
            {
                return this._Urls;
            }
            set
            {
                this._Urls = value;
            }
        }
    }
}

